const http = require('http')
const fs = require('fs')
const { log } = require('console')
const server = http.createServer((req, res) => {
    //设置请求头
    // res.setHeader("Content-type","text/html;charset=utf-8");//设置了css会失效,要动态读取文件类型
    let { pathname } = new URL(req.url, 'http://localhost:8989')
    if (pathname === '/') {
        pathname = '/index.html'
    }
    // const publicDir = __dirname.slice(0, __dirname.length - 3);
    const publicDir = '../'
    const filePath = publicDir + pathname;
    const errorPath = publicDir + '/error.html';
    fs.readFile(filePath, (error, data) => {
        if (error) { // 没有对应的文件
            const newPath = filePath + '.html';
            fs.readFile(newPath,(err,page)=>{
                if(error){
                    fs.readFile(errorPath,(err,theError)=>{
                        res.end(theError)
                    })
                }
                res.end(page)
            })

        } else {
            res.end(data)
        }
    })
})

server.listen(8989, () => {
    console.log('启动服务成功: http://localhost:8989')
})